'use strict';
import { showDialog } from 'vant';
import $config from '../config/config.js'  // eslint-disable-line no-unused-vars
/*
  util工具库
*/
class Util {
	constructor(arg) {}  // eslint-disable-line no-unused-vars

	formatDate(date) {
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		return [year, month, day].map(this.formatNumber).join('-')
	}
	formatDate2(date) {
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		return [year, month, day].map(this.formatNumber).join('_')
	}
	formatNumber(n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}
	formatRandom() {
		let code = ''
		for (var i = 0; i < 6; i++) {
			code += parseInt(Math.random() * 10)
		}
		return code
	}
	// 分钟数转换为 小时：分钟 
	ChangeHourMinutestr(str) {
		if (str !== "0" && str !== "" && str !== null) {
			return ((Math.floor(str / 60)).toString().length < 2 ? (Math.floor(str / 60)).toString() :
				(Math.floor(str / 60)).toString()) + "小时" + ((str % 60).toString().length < 2 ? (str % 60)
				.toString() : (str % 60).toString()) + "分钟";
		} else {
			return "";
		}
	}
	// 小时分钟格式转换为分钟数
	ChangeStrToMinutes(str) {
		var arrminutes = str.split(":");
		if (arrminutes.length == 2) {
			var minutes = parseInt(arrminutes[0]) * 60 + parseInt(arrminutes[1]);
			return minutes;
		} else {
			return 0;
		}
	}

	format_price(_number, _sep) {
		_number = typeof _number != "undefined" && _number > 0 ? _number + '' : "";
		if (_number.indexOf('.') != -1) {
			_number = _number.split('.')[0];
		}
		_number = _number.replace(new RegExp("^(\\d{" + (_number.length % 3 ? _number.length % 3 : 0) +
				"})(\\d{3})", "g"),
			"$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim()
		if (typeof _sep != "undefined" && _sep != " ") {
			_number = _number.replace(/\s/g, _sep);
		}
		return _number;
	}

	get_price_decimal(_price) {
		_price = _price + '';

		if (_price.indexOf('.') != -1) {
			return '.' + _price.split('.')[1];
		} else {
			_price = Math.random(2).toFixed(2);
		}

		return this.get_price_decimal(_price);
	}
	//--基于时间生成的随机订单号，具有唯一性
	setTimeDateFmt(s) { // 个位数补齐十位数
		return s < 10 ? '0' + s : s;
	}

	createordernum(type) {
		const now = new Date()
		let month = now.getMonth() + 1
		let day = now.getDate()
		let hour = now.getHours()
		let minutes = now.getMinutes()
		let seconds = now.getSeconds()
		month = this.setTimeDateFmt(month)
		day = this.setTimeDateFmt(day)
		hour = this.setTimeDateFmt(hour)
		minutes = this.setTimeDateFmt(minutes)
		seconds = this.setTimeDateFmt(seconds)
		let orderCode = type + "_test_" + now.getFullYear().toString() + month.toString() + day + hour + minutes +
			seconds + (Math.round(
				Math.random() * 1000000)).toString();
		return orderCode;
		//基于年月日时分秒+随机数生成订单编号
	}
	/**
	 * @description 数值格式化
	 */
	format_number(number) {
		try {
			number = parseFloat(number);

			if (number > 10000 * 1000) {
				return (number / (10000 * 10000)).toFixed(1) + '亿';
			}

			if (number > 10000) {
				return (number / (10000 * 1)).toFixed(1) + '万';
			}

			return number;
		} catch (e) {
			return number;
		}
	}

	/**
	 * @description float 格式化，防止 js 精度丢失
	 */
	format_float(number) {
		number = parseFloat(number);
		if (isNaN(number)) return number;

		number = parseInt(number.toFixed(2) * 100);

		return number / 100;
	}

	/**
	 * @description float 格式化，防止 js 精度丢失
	 */
	format_int(number) {
		number = parseFloat(number);
		if (isNaN(number)) return number;

		number = parseInt(number.toFixed(0));

		return number;
	}

	/**
	 * @description 全球唯一 guid
	 */
	guid() {
		return (this.__s4() + this.__s4() + "-" + this.__s4() + "-" + this.__s4() + "-" + this.__s4() + "-" + this
			.__s4() +
			this.__s4() + this.__s4());
	}
	__s4() {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	}

	/**
	 * @description 消息提示 toast
	 */
	msg(title, duration = 2100, mask = false, icon = 'none') {// eslint-disable-line no-unused-vars
		if (!title) return;
		if (typeof title !== 'string') title = JSON.stringify(title);

		// uni.showToast({
		// 	title,
		// 	duration,
		// 	mask,
		// 	icon
		// });
	}

	/**
	 * @description 消息提示 alert
	 */
	alert(content, callback, bool) {
		if (typeof content !== 'string') content = JSON.stringify(content);
		showDialog({
			title: '提示',
			content: content,
			showCancel: !bool,
			success(res) {
				if (res.confirm) {
					if (typeof callback === 'function') {
						callback(true);
					}

				} else if (res.cancel) {
					callback(false);
				}
			}
		})
	}

	/**
	 * @description 获取路径参数
	 */
	get_params(data) {
		let params = '';
		if (typeof data === 'object') {
			for (let _ in data) {
				params += '&' + encodeURIComponent(_) + '=' + encodeURIComponent(data[_]);
			}
			params = '?' + params.slice(1);
		} else if (typeof data === 'string') {
			if (data.indexOf('?') != -1) params = data;
			else params = '?' + data;
		} else {
			params = data;
		}

		return params;
	}

	/**
	 * @param {Object} url路径
	 * @description 获取路径参数对象
	 */
	request(url) {
		var href = decodeURIComponent(url || location.href).split('#')[0];
		if (href.indexOf('?') == -1) return {};

		var params = href.split('?')[1];
		if (params === "") return {};

		params = params || '';
		var obj = {};

		if (params.indexOf('&') <= -1) {
			obj[params.split('=')[0]] = params.split('=')[1];
			return obj;
		}

		var arr = params.split('&'),
			len = arr.length,
			i = 0;

		for (i = 0; i < len; i++) {
			if (arr[i] != "") {
				obj[arr[i].split('=')[0]] = arr[i].split('=')[1];
			}
		}

		return obj;
	}

	/** 
	 * @description js 判断对象是否为空 
	 * */

	isEmpty(obj) {
		if (JSON.stringify(obj) == "{}") {
			return true;
		}
		return false;
	}

	/**
	 * @description 去除两端空格
	 * */
	trim(str) {
		return str.replace(/\s+/g, "");
	}


	dom(a, b) {
		if (arguments.length === 1 && typeof arguments[0] == 'string') {
			if (document.querySelector) {
				return document.querySelector(arguments[0])
			}
		} else if (arguments.length === 2) {
			if (typeof a === 'string')
				a = this.dom(a);
			if (a.querySelector) {
				return a.querySelector(b)
			}
		}
		return a
	}

	domAll(a, b) {
		if (arguments.length === 1 && typeof arguments[0] == 'string') {
			if (document.querySelectorAll) {
				return document.querySelectorAll(arguments[0])
			}
		} else if (arguments.length === 2) {
			if (typeof a === 'string')
				a = this.dom(a);
			if (a.querySelectorAll) {
				return a.querySelectorAll(b)
			}
		}
		return a
	}

	/**
	 * @description json 数组分组
	 * */
	fomtJsonGroup(arr) {
		var map = {},
			dest = [];
		for (var i = 0; i < arr.length; i++) {
			var ai = arr[i];
			if (!map[ai.taskType]) {
				dest.push({
					taskType: ai.taskType,
					xh: ai.xh,
					jumpname: ai.jumpname,
					jumptype: ai.jumptype,
					state: ai.state,
					title: ai.title,
					condition: ai.condition,
					data: [ai]
				});
				map[ai.taskType] = ai;
			} else {
				for (var j = 0; j < dest.length; j++) {
					var dj = dest[j];
					if (dj.taskType == ai.taskType) {
						dj.data.push(ai);
						break;
					}
				}
			}
		}
		console.log(dest);
		return dest;
	}
	/**
	 * @description 打印 info 日志
	 * */
	info(msg) {
		console.info(msg)
	}

	//获取年月的开始日期和结束日期
	getMonthStart(year, month){
		var start = new Date(year, month - 1, 2);
		return start.toISOString().slice(0,10);
	}
	//获取年月的开始日期和结束日期
	getMonthEnd(year, month){
		var end = new Date(year, month, 0);
		return end.toISOString().slice(0,10);
	}
	/**
	 * 得到本周、上周、下周的起始、结束日期
	 * @param {*} type "s"代表开始,"e"代表结束
	 * @param {*} dates dates为数字类型，不传或0代表本周，-1代表上周，1代表下周
	 * @returns 
	 */
	getMonday(type, dates) {
    var now = new Date();
    var nowTime = now.getTime();
    var day = now.getDay();
    var longTime = 24 * 60 * 60 * 1000;
    var n = longTime * 7 * (dates || 0);
		var dd='';
    if (type == "s") {
        dd = nowTime - (day - 1) * longTime + n;
    }
    if (type == "e") {
        dd = nowTime + (7 - day) * longTime + n;
    }
    dd = new Date(dd);
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;
    var d = dd.getDate();
    m = m < 10 ? "0" + m: m;
    d = d < 10 ? "0" + d: d;
    day = y + "-" + m + "-" + d;
    return day;
	}
	/**
	 * 得到本月、上月、下月的起始、结束日期
	 * @param {*} type "s"代表开始,"e"代表结束
	 * @param {*} months months为数字类型  0代表本月，-1代表上月，1代表下月 
	 * @returns 
	 */
	getMonth(type, months) {
    var d = new Date();
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    if (Math.abs(months) > 12) {
        months = months % 12;
    }
    if (months != 0) {
        if (month + months > 12) {
            year++;
            month = (month + months) % 12;
        } else if (month + months < 1) {
            year--;
            month = 12 + month + months;
        } else {
            month = month + months;
        }
    }
    month = month < 10 ? "0" + month: month;

    var firstday = year + '-' + month + '-' + '01';
    var lastday = "";
    if (month == "01" || month == "03" || month == "05" || month == "07" || month == "08" || month == "10" || month == "12") {
        lastday = year + "-" + month + "-" + 31;
    } else if (month == "02") {
        if ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0)) {
            lastday = year + "-" + month + "-" + 29;
} else {
            lastday = year + "-" + month + "-" + 28;
        }
    } else {
        lastday = year + '-' + month + '-' + 30;
    }
    var day = "";
    if (type == "s") {
        day = firstday;
    } else {
        day = lastday;
    }
    return day;
}


}

export default new Util()